package graph.hard;

import java.util.PriorityQueue;

public class TrappingRainWaterII_407 {

    public int trapRainWater(int[][] heightMap) {
        int[][] dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        int m = heightMap.length, n = heightMap[0].length;

        boolean[][] visited = new boolean[m][n];
        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> a[2] - b[2]);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    visited[i][j] = true;
                    queue.offer(new int[]{i, j, heightMap[i][j]});
                }
            }
        }
        int res = 0;
        while (!queue.isEmpty()) {

            int[] poll = queue.poll();
            for (int[] ints : dir) {
                int x = poll[0] + ints[0], y = poll[1] + ints[1];
                if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y]) {
                    if (poll[2] > heightMap[x][y]) {
                        res += poll[2] - heightMap[x][y];
                    }
                    queue.offer(new int[]{x, y, Math.max(heightMap[x][y], poll[2])});
                    visited[x][y] = true;
                }
            }

        }

        return res;
    }
}
